﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace UniRlv.Server
{
    public partial class Form1 : Form
    {
        ServerOprImp srv = new ServerOprImp();
        TcpServerChannel channel;
        bool canDel = true;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lbTip.Text = "服务器初始化中...";
            #region 使用Tcp信道
            //客户端注册服务端事件
            BinaryServerFormatterSinkProvider serverProvider =
                new BinaryServerFormatterSinkProvider();

            serverProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
            IDictionary dict = new Hashtable();

            dict["port"] = ConfigurationHelper.AppGetInt("port");
            dict["name"] = "UniRlvChanel";

            if (!string.IsNullOrEmpty(ConfigurationHelper.AppGetString("localIP")))
            {
                dict["bindTo"] = ConfigurationHelper.AppGetString("localIP");
            }

            channel = new TcpServerChannel(dict, serverProvider);
            ChannelServices.RegisterChannel(channel, false);

            RemotingConfiguration.ApplicationName = "UniRlvSolu";

            #endregion

            //客户端注册服务端事件
            RemotingServices.Marshal(srv, "UniRlv");
            lbTip.Text = "服务器初始化完成: " + channel.GetChannelUri();

            string msg = string.Empty;

            if (srv.IfTableExist("PrintInfo"))
            {
                Console.WriteLine("PrintInfo table exist!");
            }
            else
            {
                Console.WriteLine("PrintInfo table no exist!");
                string sql = "CREATE TABLE [dbo].[PrintInfo]([id] [int] IDENTITY(1,1) NOT NULL,[taskID] [int] NOT NULL,[stationNum] [int] NOT NULL,[subDeviceNum] [int] NULL,[name] [nvarchar](50) NOT NULL,[initString] [nvarchar](200) NULL,[templatePath] [nvarchar](500) NOT NULL,[codePath] [nvarchar](500) NOT NULL,[printWord] [int] NULL,[printQty] [int] NOT NULL,CONSTRAINT [PK_PrintInfo] PRIMARY KEY CLUSTERED ([id] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]";
                

                srv.ExecuteNonQuery(sql, 112233, ref msg);
            }

            if (!srv.IfColumnExist("ProductionTask", "spm"))
            {
                Console.WriteLine("spm column no exist!");

                srv.AddColumn("ProductionTask", "spm", 112233, "varchar(100)", ref msg);
            }

            if (!srv.IfColumnExist("CompanyInfo", "phone"))
            {
                Console.WriteLine("phone column no exist!");

                srv.AddColumn("CompanyInfo", "phone", 112233, "varchar(20)", ref msg);
            }

            if (!srv.IfColumnExist("ProductionTask", "operateDate"))
            {
                Console.WriteLine("operateDate column no exist!");

                srv.AddColumn("ProductionTask", "operateDate", 112233, "datetime DEFAULT (getdate())", ref msg);
            }

            btnRefresh.PerformClick();

            BkDB();

            tmDBBK.Enabled = true;
            tmDBBK.Start();

            this.ShowInTaskbar = false;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            string dir = ConfigurationHelper.AppGetString("updateDir");
            string path = Path.Combine(Application.StartupPath, dir);

            if (Directory.Exists(path))
            {
                IEnumerable<string> localFiles = Directory.EnumerateFiles(path, "*.dll", SearchOption.TopDirectoryOnly).Union(Directory.EnumerateFiles(path, "*.exe", SearchOption.TopDirectoryOnly));

                Dictionary<string, string> dict = new Dictionary<string, string>();
                FileVersionInfo fv;
                string fileName;

                listBox1.Items.Clear();

                foreach (string item in localFiles)
                {
                    fileName = Path.GetFileName(item);

                    fv = System.Diagnostics.FileVersionInfo.GetVersionInfo(item);
                    dict.Add(fileName, fv.ProductVersion);

                    listBox1.Items.Add(string.Format("{0} V{1}", fileName, fv.ProductVersion));
                }
            }

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (channel != null)
            {
                ChannelServices.UnregisterChannel(channel);
            }

            tmDBBK.Stop();
            tmDBBK.Enabled = false;
        }

        private void toolMenuQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
                this.notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
            this.Show();
        }

        private void tmDBBK_Tick(object sender, EventArgs e)
        {
            //查询是否需要备份数据库

            if (IfInBkTime())
            {//当前时间是可备份时间
                if (canDel)
                {
                    BkDB();
                    canDel = false;
                    return;
                }

            }
            else
            {
                canDel = true;
            }
        }

        void BkDB()
        {
            int p = ConfigurationHelper.AppGetInt("dbBKPeriod");
            ThreadPool.QueueUserWorkItem(new WaitCallback(BackupDBThread), p);
            string msg = string.Empty;

            SqlParameter[] sp = new SqlParameter[4];

            sp[0] = new SqlParameter("@InStrPara", SqlDbType.VarChar, 1024);

            sp[1] = new SqlParameter("@wp", SqlDbType.Int);
            sp[1].Value = p;

            sp[2] = new SqlParameter("@lp", SqlDbType.Int);

            sp[3] = new SqlParameter("@Res", SqlDbType.Int);
            sp[3].Direction = ParameterDirection.Output;

            SqlHelper.ExecuteNonQueryProc("uni_backup_code", ref msg, sp);

            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff]") + "开始备份数据库");
            if (!string.IsNullOrEmpty(msg))
            {
                Console.WriteLine("备份数据库错误：" + msg);
            }
            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff]") + "结束备份数据库");
        }

        void BackupDBThread(object obj)
        {
            int p = Convert.ToInt32(obj);
        }

        bool IfInBkTime()
        {
            //判断当前时间是否在工作时间段内
            string _strWorkingDayAM = "23:50:00";
            string _strWorkingDayPM = "23:59:59";
            TimeSpan dspWorkingDayAM = DateTime.Parse(_strWorkingDayAM).TimeOfDay;
            TimeSpan dspWorkingDayPM = DateTime.Parse(_strWorkingDayPM).TimeOfDay;

            TimeSpan dspNow = DateTime.Now.TimeOfDay;
            if (dspNow > dspWorkingDayAM && dspNow < dspWorkingDayPM)
            {
                return true;
            }

            return false;
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            if (srv.TestConnect(ref msg))
            {
                MessageBox.Show("连接成功");
            }
            else
            {
                MessageBox.Show("连接失败：" + msg);
            }
        }
    }
}
